package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据id查询商铺信息,并存入数据库
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {

        //缓存穿透
        Shop shop = queryWithPassThrough(id);

        //互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿
        //Shop shop = queryWithLogicalExpire(id);

        if (shop==null){
            return Result.fail("店铺不存在");
        }


        return Result.ok(shop);
    }


    public Shop queryWithLogicalExpire(Long id){
        String key=CACHE_SHOP_KEY+id;
        //1.从Redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.命中数据返回
        if (StrUtil.isBlank(shopJson)){
            return null;
        }




        //3.未命中查询数据库
        Shop shop = getById(id);
        //4.将数据存入Redis
        stringRedisTemplate.opsForValue()
                .set(key,JSONUtil.toJsonStr(shopJson),3, TimeUnit.SECONDS);
        //5.返回
        return shop;
    }

    public Shop queryWithMutex(Long id){
        String key=CACHE_SHOP_KEY+id;
        //1.从Redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.命中数据返回
        if (StrUtil.isNotBlank(shopJson)){
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断是否为空
//        if (shopJson==null){
//            return null;
//        }
        /**
         * 获取互斥锁
         */
        String lockKey="lock:shop"+id;
        Shop shop = null;
        try {
            boolean shopLock = tryLock(lockKey);
            if (!shopLock){
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //3.未命中查询数据库
            shop = getById(id);
            //3.1数据库未命中返回错误信息
            if (shop==null){
                //将查询到的空信息存入Redis
                stringRedisTemplate.opsForValue()
                        .set(key,"",1, TimeUnit.SECONDS);
                return null;
            }
            //4.将数据存入Redis
            stringRedisTemplate.opsForValue()
                    .set(key,JSONUtil.toJsonStr(shopJson),3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unlock(lockKey);
        }
        //5.返回
        return shop;
    }

    public Shop queryWithPassThrough(Long id){
        String key=CACHE_SHOP_KEY+id;
        //1.从Redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.命中数据返回
        if (StrUtil.isNotBlank(shopJson)){
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //3.未命中查询数据库
        Shop shop = getById(id);
        //3.1数据库未命中返回错误信息
        if (shop==null){
            //将查询到的空信息存入Redis
            stringRedisTemplate.opsForValue()
                    .set(key,"",1, TimeUnit.SECONDS);
            return null;
        }
        //4.将数据存入Redis
        stringRedisTemplate.opsForValue()
                .set(key,JSONUtil.toJsonStr(shop),3, TimeUnit.SECONDS);
        //5.返回
        return shop;
    }

    /**
     * 获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue()
                .setIfAbsent(key, "", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 删除锁
     * @param key
     * @return
     */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 封装店铺信息与逻辑过期时间
     * @param id
     * @param expireSeconds
     */
    private void saveShop2Redis(Long id,Long expireSeconds){
        //1.查询店铺数据
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入Redis
        stringRedisTemplate.opsForValue()
                .set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }



    /**
     * 更新商铺信息
     * @param shop 商铺数据
     * @return 无
     */
    @Override
    @Transactional  //事务注解，要么同时成功，要么同时失败
    public Result updateId(Shop shop) {
        //1.判断店铺id是否为空
        Long id = shop.getId();
        if (id==null){
            return Result.fail("店铺信息错误！");
        }
        //2.更新数据库
        updateById(shop);
        //3.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }
}
